package org.ishequ.db;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.ishequ.domain.ShortMessage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SMSDBService {
	private DBOpenHelper openHelper ;
	
	public SMSDBService(Context context){
		openHelper = new DBOpenHelper(context);
	}
	
	public void insert(ShortMessage sms){
		SQLiteDatabase db = openHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("sender", sms.getSender());
		values.put("receiver", sms.getReceiver());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		values.put("receiverTime", sdf.format(sms.getReceiveTime()));
		values.put("content", sms.getContent());
		db.insert("sms", null, values);
	}
	
	public void delete(long id){
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.delete("sms", "id=?", new String[]{String.valueOf(id)});
	}
	
	public List<ShortMessage> query(String selection,String[] args) throws ParseException{
		List<ShortMessage> messages = new ArrayList<ShortMessage>();
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.query("sms", new String[]{"id","sender","receiver","receiverTime","content"},
					selection, args, "", "", "receiverTime desc");
		while(cursor.moveToNext()){
			String receiver = cursor.getString(cursor.getColumnIndex("receiver"));
			String sender = cursor.getString(cursor.getColumnIndex("sender"));
			Date receiveTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(cursor.getString(cursor.getColumnIndex("receiverTime")));
			String content = cursor.getString(cursor.getColumnIndex("content"));
			long id = cursor.getLong(cursor.getColumnIndex("id"));
			messages.add(new ShortMessage(id,receiver,sender,receiveTime,content));
		}
		cursor.close();
		return messages;
	}
	
	public void close(){
		openHelper.close();
	}
	
}
